package com.yami.shop.api.utils;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.handler.HttpHandler;
import com.yami.shop.common.response.ResponseEnum;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.security.common.bo.UserInfoInTokenBO;
import com.yami.shop.security.common.manager.TokenStore;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.reactive.result.view.RequestContext;

@Log4j2
public class UserInfoUtils {

    public static UserInfoInTokenBO getUserInfo(TokenStore tokenStore){
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        // 判断 RequestAttributes 是否为空
        if (requestAttributes instanceof ServletRequestAttributes) {
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
            // 获取 Header 信息
            String accessToken = request.getHeader("Authorization");
                // 如果有token，就要获取token
                if (StrUtil.isNotBlank(accessToken)) {
                    // 校验登录，并从缓存中取出用户信息
                    try {
                        StpUtil.checkLogin();
                    } catch (Exception e) {
                        throw new RuntimeException("未登录！");
                    }
                    UserInfoInTokenBO userInfoByAccessToken = tokenStore.getUserInfoByAccessToken(accessToken, true);
                    return userInfoByAccessToken;
                }
        } else {
            // 如果 RequestAttributes 不是 ServletRequestAttributes 类型，则无法获取 HttpServletRequest 对象
            log.info("Cannot get HttpServletRequest from RequestContextHolder");
        }
        return null;
    }

}
